package com.samapp.indent;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.dragon.httpclient_util.HttpClientThread;
import com.dragon.httpclient_util.HttpResultHandle;
import com.dragon.httpclient_util.JsonUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.samapp.MyApplication;
import com.samapp.R;
import com.samapp.review.ReviewIndentActivity;
import com.samapp.utils.Common;
import com.samapp.utils.json.GsonUtil;

public class AutographActivity extends Activity implements OnClickListener {

	/** 签名 */
	private ImageView imageAutograph = null;
	/** 上传签名并创建订单 */
	private Button btnUploadingAutograph = null;
	/** 上一步 */
	private Button btnFront = null;
	/** 签名请求码 */
	public static final int CODE_AUTOGRAPH = 0xa0;
	/** 上传签名 */
	public static final int MSG_UP_AUTOGRAPH = 0X193;
	/** 创建订单 */
	public static final int MSG_CREATE_INDENT = 0X194;
	/** 上传结果信息 */
	private String upAutographInfo;
	/**签名文件路径*/
	String imagePath = "";
	/** 创建订单信息 */
	private String createOrderInfo;
	
	private Bitmap mSignBitmap;

	private MyApplication myApplication = MyApplication.getApplicationInstance();

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MSG_UP_AUTOGRAPH) {
				Toast.makeText(AutographActivity.this, upAutographInfo, Toast.LENGTH_SHORT).show();
			} else if (msg.what == MSG_CREATE_INDENT) {
				Toast.makeText(AutographActivity.this, createOrderInfo, Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_autograph);
		init();
	}

	private void init() {
		initView();
		initListener();
	}

	private void initView() {
		imageAutograph = (ImageView) findViewById(R.id.image_autograph);
		btnUploadingAutograph = (Button) findViewById(R.id.btn_uploading_autograph);
		btnFront = (Button) findViewById(R.id.btn_front);
	}

	private void initListener() {
		imageAutograph.setOnClickListener(this);
		btnUploadingAutograph.setOnClickListener(this);
		btnFront.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image_autograph:
			createSignFile();
			break;
		case R.id.btn_uploading_autograph:
			uploadingAutograph();
			break;
		case R.id.btn_front:
			skip(ReviewIndentActivity.class);
			finish();
			break;
		}
	}
	
	private void createSignFile(){
		WritePadDialog writeTabletDialog = new WritePadDialog(
				AutographActivity.this, new DialogListener() {
					@Override
					public void refreshActivity(Object object) {							
						mSignBitmap = (Bitmap) object;
						imagePath = createFile();													
						imageAutograph.setImageBitmap(mSignBitmap);
					}
				});
		writeTabletDialog.show();
	}
	
	/**
	 * 创建手写签名文件
	 * 
	 * @return
	 */
	private String createFile() {
		ByteArrayOutputStream baos = null;
		String _path = null;
		try {
			String sign_dir = Environment.getExternalStorageDirectory() + File.separator;			
			_path = sign_dir + System.currentTimeMillis() + ".jpeg";
			baos = new ByteArrayOutputStream();
			mSignBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			byte[] photoBytes = baos.toByteArray();
			if (photoBytes != null) {
				new FileOutputStream(new File(_path)).write(photoBytes);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null)
					baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return _path;
	}

	/**
	 * 上传签名
	 */
	private void uploadingAutograph() {
		if(imagePath.equals("")){
			createOrderInfo = "请先手写签名确认";
			mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
			return;
		}
		
		String url = myApplication.url + "uploadImg.htm";
		RequestParams params = new RequestParams();
		params.addBodyParameter("accessToken", "5C9.yx0S");
		params.addBodyParameter("type", Common.UP_AUTOGRAPH);
		params.addBodyParameter("file", new File(imagePath));
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				Log.i("Long", arg0.result);
				upAutographInfo = JsonUtils.getValue(arg0.result, "msg");
				mHandler.sendEmptyMessage(MSG_UP_AUTOGRAPH);
				myApplication.newIndent.setSignPath(JsonUtils.getValue(arg0.result, "path"));
				
				saveOrderData();
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Log.i("Long", arg1);
				upAutographInfo = JsonUtils.getValue(arg1, "msg");
				mHandler.sendEmptyMessage(MSG_UP_AUTOGRAPH);
			}
		});
	}
	
	private void saveOrderData(){
		String url = myApplication.url + "createOrder.htm";
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("accessToken", "5C9.yx0S");
		myMap.put("cnumber", myApplication.newIndent.getCnumber());
		myMap.put("number", myApplication.newIndent.getNumber());
		myMap.put("busType", myApplication.newIndent.getBusType());
		myMap.put("fetchType", myApplication.newIndent.getFetchType());
		myMap.put("lceType", myApplication.newIndent.getLceType());
		myMap.put("unumber", myApplication.newIndent.getUnumber());
		myMap.put("Language", myApplication.newIndent.getLanguage());
		myMap.put("isUrgent", myApplication.newIndent.getIsUrgent());
		myMap.put("isPacket", myApplication.newIndent.getIsPacket());
		myMap.put("isReturn", myApplication.newIndent.getIsReturn());
		myMap.put("isSms", myApplication.newIndent.getIsSms());
		myMap.put("remark", myApplication.newIndent.getRemark());
		myMap.put("signPath", myApplication.newIndent.getSignPath());
		myMap.put("orderDetail", GsonUtil.getGson().toJson(myApplication.newIndent.getOrderDetail()));
		myMap.put("samples", GsonUtil.getGson().toJson(myApplication.newIndent.getSamples()));
		HttpClientThread.getmHttpClientThread().post(url, myMap, new HttpResultHandle() {

			@Override
			public void onSuccess(String response) {
				String code = JsonUtils.getValue(response, "code");
				if ("0".equals(code)) {
					// text[0] = JsonUtils.getValue(response, "discount");
					createOrderInfo = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
					finish();
				} else {
					createOrderInfo = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
				}
			}

			@Override
			public void onFailure(int statusCode) {
				createOrderInfo = "连接服务器失败，状态码：" + statusCode;
				mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
			}
		});
	}
	
	/** 跳转页面 */
	private void skip(Class<?> cls) {
		Intent intent = new Intent(this, cls);
		startActivity(intent);
	}

	/** 修改返回键 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		btnFront.performClick();
	}
}
